<template>
  <div id="app">
    <van-config-provider
      :theme-vars="{
        // 主题色
        buttonPrimaryBackground: '#02cc66',
        buttonPrimaryBorderColor: '#02cc66',

        // 顶部栏
        navBarHeight: '60px',
      }"
    >
      <router-view v-slot="{ Component }" v-if="isInit">
        <keep-alive :include="['cache']">
          <component :is="Component"></component>
        </keep-alive>
      </router-view>
    </van-config-provider>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '@/store/index'
import { useI18n } from 'vue-i18n'
import { showToast } from 'js/utils'
import cosmo from 'cosmo-wallet-tool'

// 全局国际化语言变量注入
const { t, locale } = useI18n()
window.$t = t
window.locale = locale

const router = useRouter()
const route = useRoute()
const store = useStore()

// 是否已初始化
const isInit = ref(false)

initWallet()

// 初始化钱包
async function initWallet() {
  try {
    const isWallet = await cosmo.isWallet
    const isChrome = await cosmo.isChrome

    if (isWallet || isChrome) {
      // 在可运行的环境内
      const result = await cosmo.getPermission()
      let permission = result && result.length !== 0

      if (permission) {
        // 已授权
        getFromAddress()
      } else {
        // 未授权
        permission = await cosmo.applyPermission()

        if (permission) {
          getFromAddress()
        }
      }
    } else {
      showToast('请在Cosmo Wallet或Chrome浏览器打开')
    }
  } catch (err) {
    console.log(err)
    showToast('获取钱包地址失败')
  }
}

// 获取钱包地址
async function getFromAddress() {
  try {
    const fromAddress = await cosmo.getAccount()

    if (fromAddress) {
      window.fromAddress = fromAddress
      window.fromAddressHide = fromAddress.replace(
        fromAddress.slice(3, 38),
        '*******'
      )

      console.log('钱包地址：', fromAddress)

      if (!store.userInfo?.token) {
        // 未登录
        const inviteId = route.query.inviteId || ''
        router.replace(`/login?inviteId=${inviteId}`)
      }

      setTimeout(() => {
        isInit.value = true
      }, 100)
    } else {
      showToast('获取钱包地址失败')
    }
  } catch (err) {
    console.log(err)
    showToast('获取钱包地址失败')
  }
}
</script>

<style lang="scss">
@import 'style/index.scss';

#app {
  max-width: 400px;
  margin: 0 auto;
}
</style>
